package com.manor.main.activity

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.google.android.material.appbar.AppBarLayout
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.enums.PopupPosition
import com.lxj.xpopup.enums.PopupType
import com.lxj.xpopup.interfaces.OnSelectListener
import com.lxj.xpopup.interfaces.SimpleCallback
import com.orhanobut.logger.Logger
import com.manor.common.CommonAppConfig
import com.manor.common.Constants
import com.manor.common.activity.AbsActivity
import com.manor.common.bean.ChatReceiveGiftBean
import com.manor.common.bean.UserNBean
import com.manor.common.event.FollowEvent
import com.manor.common.event.GiftShowEvent
import com.manor.common.http.CommonHttpUtil
import com.manor.common.utils.*
import com.manor.common.interfaces.CommonCallback
import com.manor.common.ktx.setBindViewPager
import com.manor.common.presenter.GiftAnimViewHolder
import com.manor.common.presenter.OnChatListener
import com.manor.dynamic.activity.DynamicPublishActivity
import com.manor.dynamic.dialog.DynamicLookImgDialogFragment
import com.manor.dynamic.views.ViewSizeChangeAnimation
import com.manor.im.activity.HChatRoomActivity
import com.manor.im.bean.GuardPriceBean
import com.manor.im.dialog.ChatGiftDialog
import com.manor.im.http.ImHttpUtil.getGuardPrice
import com.manor.im.presenter.CheckChatPresenter
import com.manor.im.utils.VoiceMediaPlayerUtil
import com.manor.main.R
import com.manor.main.adapter.UserCenterTabAdapter
import com.manor.main.fragment.user.*
import com.manor.main.http.MainHttpUtil
import com.manor.video.activity.VideoPublishActivity
import com.blankj.utilcode.util.ConvertUtils
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMMessage
import com.tencent.imsdk.v2.V2TIMSendCallback
import com.tencent.qcloud.tim.uikit.modules.message.MessageInfoUtil
import com.tencent.rtmp.TXVodPlayer
import com.tencent.rtmp.ui.TXCloudVideoView
import kotlinx.android.synthetic.main.activity_user_center.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import java.math.BigDecimal
import java.util.*
import kotlin.math.abs


/**
 * 用户资料中心
 * @date  2020/7/14  10:37
 * @version 1.0
 */
@Route(path = RouteUtil.PATH_PERSONAL_CENTER)
class UserCenterActivity : AbsActivity() {
    private var mUid = ""
    private var voicePath: String = ""
    private var nickName: String = ""
    private var isLoadVoice = false
    private var isFirst = true
    private var mTypeMine = true
    private var mDownloadUtil: DownloadUtil? = null
    private lateinit var mAdapter: UserCenterTabAdapter
    private var openVoice = false
    private var openVideo = false
    private var mUserNBean: UserNBean? = null
    private var mCheckChatPresenter: CheckChatPresenter? = null
    private var mChatType = 0
    private var mGiftAnimViewHolder: GiftAnimViewHolder? = null
    internal var mScreenHeight: Int = 0
    internal var mScreenWidth: Int = 0

    companion object {
        fun forward(context: Context, uId: String) {
            Intent(context, UserCenterActivity::class.java).apply {
                putExtra(Constants.TO_UID, uId)
                context.startActivity(this)
            }
        }
    }

    override fun getLayoutId(): Int = R.layout.activity_user_center


    override fun main() {
        super.main()
        prepareView(intent)
        EventBus.getDefault().register(this)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        prepareView(intent)
    }

    private fun prepareView(mIt: Intent?) {
//        ImmersionBar.with(this).statusBarColor(R.color.main_bg).init()
        mUid = mIt?.getStringExtra(Constants.TO_UID) ?: ""
        if (mUid.isNullOrEmpty()) {
            return
        }

        mTypeMine = mUid == CommonAppConfig.getInstance().uid
        setTypeUI()
        mScreenHeight = ScreenDimenUtil.getInstance().screenHeight
        mScreenWidth = ScreenDimenUtil.getInstance().screenWdith
        val fragmentList = listOf(
                //UserVideoFragment.newInstance(mUid),
//                UserVideoNewFragment.newInstance(mUid),
//                UserAlbumFragment.newInstance(mUid),
                UserDynamicFragment.newInstance(mUid),
                UserBasicFragment.newInstance(mUid)
        )
//        val titles = listOf("视频", "相册", "社区动态", "基本信息")
        val titles = listOf("淘米圈动态", "商家信息")
        mAdapter = UserCenterTabAdapter(this, fragmentList)
        mViewPager.adapter = mAdapter
        tabLayout.setBindViewPager(mViewPager, titles)
        initViews()
    }

    private fun initViews() {
        mViewPager.registerOnPageChangeCallback(pageChangeCallback)
//        appBarLayout.addOnOffsetChangedListener(offsetChangeListener)
        ivAddFab.setOnClickListener { doFabAdd() }
        ivTBack.setOnClickListener {
            //UserSvManager.clearDataSource()
            finish()
        }
        tvUserSign.setOnClickListener {
            if (mTypeMine && canClick())
                mContext?.startActivity(Intent(mContext, EditUserInfoActivity::class.java))
        }
        ivUser.setOnClickListener {
            mUserNBean?.run {
                lookImgs(arrayListOf(this.basics.avatar), 0, object : CommonCallback<Boolean>() {
                    override fun callback(bean: Boolean?) {
                    }
                })
            }
        }
        mVoicePlayView.setOnClickListener { playVoice(voicePath) }
        ivFabGift.setOnClickListener { senGift(false) }
        ivFabMineGift.setOnClickListener { senGift(false) }
        ivFabGuard.setOnClickListener { getGuardInfo() }
        ivFabMore.setOnClickListener { showBottomMenu() }
        tvEdit2Fav.setOnClickListener {
            if (mTypeMine)
                mContext?.startActivity(Intent(mContext, EditUserInfoActivity::class.java))
            else
                CommonHttpUtil.setAttention(mUid, null)
        }
    }


    override fun onPause() {
        super.onPause()
        if (this.isFinishing) {
            //进行数据操作及释放资源等操作
            if (mVoicePlayView != null) {
                mVoicePlayView.pause()
                mVoicePlayView.release()
            }
        } else {
            if (mVoicePlayView != null) {
                mVoicePlayView.resetView()
            }
        }

    }

    override fun onResume() {
        super.onResume()
        isLoadVoice = false
        doNet()


    }

    override fun onStop() {


        super.onStop()
        mCheckChatPresenter?.cancel()
        mCheckChatPresenter = null
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        if (null != mPlayer) {
            mPlayer?.stopPlay(false)
        }
        super.onDestroy()
    }

    private fun setTypeUI() {
        tvTTitle.text = if (mTypeMine) "商家主页" else "商家主页"
//        llBottom.setGone(mTypeMine)
        if (mTypeMine) {
            tvEdit2Fav.text = "编辑资料"
            tvEdit2Fav.isSelected = true
        } else {

        }
    }


    private fun doNet() {
        MainHttpUtil.getBaseInfo(mUid, object : CommonCallback<UserNBean>() {
            override fun callback(bean: UserNBean?) {
                mUserNBean = bean
                bean?.basics?.run {
                    if (!isActDestroy(this@UserCenterActivity))
                        Glide.with(this@UserCenterActivity)
                                .load(bean.basics.avatar_thumb)
                                .error(R.mipmap.default_user_icon)
                                .apply(RequestOptions().transform(CenterCrop(), CircleCrop()))
                                .into(ivUser)


//                    //判断是否是达人否认证
                    setStand(bean.basics.immortal, bean.basics.isauth, ivTagApprove)
//                    //判断是否是达人
//                    setStand(bean.basics.level_icon, ivTagStar)
//                    //判断是否是贵族
//                    setStand(bean.basics.gzu_icon, ivTagNoble)
//                    //判断是否是优质
//                    //setStand(bean.basics.quality, ivQua)




                    tvLikeNum.text = this.live
                    tvFsNum.text = this.fs
                    tvThNum.text = this.luxury
                    tvMLNum.text = this.charm
                    tvUserName.text = this.user_nickname

                    mVoicePlayView.setGone(StringUtil.isEmpty(signavoice))

                    openVoice = this.isvoice == "1"
                    openVideo = this.isvideo == "1"

                    if (!mTypeMine) {
                        tvEdit2Fav.text = if (this.isAttent == "1") "已关注" else "+关注"
                        tvEdit2Fav.isSelected = this.isAttent != "1"
                    }

                    tvAge.text = this.age
                    if ("1" == this.sex) {
                        tvAge.leftDrawable = mContext.getDrawable(R.mipmap.gender_nan)
                        //tvAge.background = mContext.getDrawable(R.drawable.shape_item_city_gendernanbg)
                    } else {
                        tvAge.leftDrawable = mContext.getDrawable(R.mipmap.gender_nv)
                        //tvAge.background = mContext.getDrawable(R.drawable.shape_item_city_bg)
                    }

                    tvSDNum.text = "淘米号：${this.serial_no}"
                    tvUserSign.text = if (this.signature.isNullOrEmpty()) "此处为个人简介，点击修改..." else this.signature

                    voicePath = this.signavoice
                    nickName = this.user_nickname.toString()
                    if (!isLoadVoice && StringUtil.isNotEmpty(voicePath) && isFirst) {
                        Logger.e("loadData isFirst voicePath==$voicePath")
                        playVoice(voicePath)
                        isFirst = false
                    }

                }
            }

        })
    }


    /**
     * 播放语音
     */
    private fun playVoice(voiceLink: String) {
        if (TextUtils.isEmpty(voiceLink)) {
            return
        }
        val fileName = MD5Util.getMD5(voiceLink)
        val path = CommonAppConfig.VOICE_PATH + fileName
        val file = File(path)
        if (file.exists() && file.length() > 0) {
            loadVoice(file.absolutePath)
            if (mVoicePlayView != null) mVoicePlayView.onClickVoice()
        } else {
            if (mDownloadUtil == null) {
                mDownloadUtil = DownloadUtil()
            }
            mDownloadUtil?.run {
                download("voice", CommonAppConfig.VOICE_PATH, fileName, voiceLink.replace(" ".toRegex(), "%20"),
                        object : DownloadUtil.Callback {
                            override fun onSuccess(file: File) {
                                loadVoice(file.absolutePath)
                                if (mVoicePlayView != null) mVoicePlayView.onClickVoice()
                            }

                            override fun onProgress(progress: Int) {}
                            override fun onError(e: Throwable) {
                                ToastUtil.show(WordUtil.getString(com.manor.dynamic.R.string.video_play_error))
                                mVoicePlayView.isClickable = false
                            }
                        })
            }

        }
    }


    private fun loadVoice(filePath: String?) {
        if (!isLoadVoice) {
            isLoadVoice = true
            mVoicePlayView.setVoiceInfo(MediaUtil.getInstance().getDuration(filePath), voicePath)
            mVoicePlayView.setVoiceMediaPlayerUtil(VoiceMediaPlayerUtil(mContext))
            mVoicePlayView.setVoicePlayCallBack {
                //pauseVoice();
            }
        }
    }

    private fun senGift(isGuard: Boolean) {
        mUserNBean?.run {
            ChatGiftDialog.forward(supportFragmentManager, basics.id, isGuard, "0", object : ChatGiftDialog.ActionListener {
                override fun onChargeClick() {
                    RouteUtil.forwardPath(RouteUtil.PC_WEB, StaIntentUtil.QUICK_RECHARGE)
                }

                override fun onGiftSend(info: String, call: CommonCallback<Boolean>) {

                    val msgInfo = MessageInfoUtil.buildCustomMessage(info)

                    V2TIMManager.getMessageManager().sendMessage(msgInfo.timMessage, mUid, null, V2TIMMessage
                            .V2TIM_PRIORITY_DEFAULT, false, null, object : V2TIMSendCallback<V2TIMMessage> {
                        override fun onSuccess(v2TIMMessage: V2TIMMessage?) {
                            call.callback(true)
                        }

                        override fun onProgress(progress: Int) {

                        }

                        override fun onError(code: Int, desc: String?) {
                            call.callback(false)
                        }

                    })


                }
            })
        }
    }

    private fun getGuardInfo() {
        mUserNBean?.run {
            getGuardPrice(basics.id, object : CommonCallback<GuardPriceBean?>() {
                override fun callback(bean: GuardPriceBean?) {
                    if (bean != null) {
//                        GuardDialogFragment.forward(supportFragmentManager, basics.avatar_thumb, bean.order.money) {
//                            it?.let { senGift(true) }
//                        }
                    }
                }
            })
        }
    }

    private fun showBottomMenu() {
        if (mTypeMine)
            return
        val imgList: MutableList<Int> = ArrayList()
        imgList.add(Constants.TYPE_CHAT_MSG)
        if (openVideo) imgList.add(Constants.TYPE_CHAT_VIDEO)
        if (openVoice) imgList.add(Constants.TYPE_CHAT_CELL)

//        XPopup.Builder(this)
//                .hasShadowBg(false)
//                .setPopupCallback(object : SimpleCallback() {
//                    override fun beforeShow(popupView: BasePopupView?) {
//                        super.beforeShow(popupView)
//                        ivFabMore?.visibility = View.INVISIBLE
//                    }
//
//                    override fun onDismiss(popupView: BasePopupView?) {
//                        super.onDismiss(popupView)
//                        ivFabMore?.visibility = View.VISIBLE
//                    }
//                })
//                .popupType(PopupType.AttachView)
//                .popupPosition(PopupPosition.Left)
//                .atView(viewX) // 依附于所点击的View，内部会自动判断在上方或者下方显示
//                .asCustom(YsyPopup(this, 1, imgList, OnSelectListener { position1: Int, text: String? ->
//                    when (position1) {
//                        Constants.TYPE_CHAT_MSG -> onMsgClick()
//                        Constants.TYPE_CHAT_VIDEO -> onVideoClick()
//                        Constants.TYPE_CHAT_CELL -> onVoiceClick()
//                    }
//                }))
//                .show()
    }

    private fun onVideoClick() {
        mChatType = Constants.CHAT_TYPE_VIDEO.toInt()
        ByCallUtil.checkPermission(this, object : OnChatListener {
            override fun doChatClick() {
                chatAudToAncStart(mChatType)
            }
        })
    }

    private fun onVoiceClick() {
        mChatType = Constants.CHAT_TYPE_VOICE.toInt()
        ByCallUtil.checkPermission(this, object : OnChatListener {
            override fun doChatClick() {
                chatAudToAncStart(mChatType)
            }

        })
    }


    private fun chatAudToAncStart(type: Int) {
        if (mCheckChatPresenter == null) {
            mCheckChatPresenter = CheckChatPresenter(mContext)
        }
        val user = ByCallUtil.convertUserInfo(mUserNBean)
        user?.run {
            mCheckChatPresenter?.chatAudToAncStart(user.id, type, user)
        }

    }


    private fun setStand(url: String?, imageView: ImageView) {
        if (StringUtil.isNotEmpty(url)) {
            imageView.visibility = View.VISIBLE
            if (!isActDestroy(this@UserCenterActivity))
                Glide.with(this@UserCenterActivity).load(url).into(imageView)
        } else {
            imageView.visibility = View.GONE
        }
    }

    private fun setStand(url: String?, isAuth: String, imageView: ImageView) {
        if (StringUtil.isNotEmpty(isAuth) && StringUtil.isNotEmpty(url)) {
            imageView.visibility = View.VISIBLE
            if (!isActDestroy(this@UserCenterActivity))
                Glide.with(this@UserCenterActivity).load(url).into(imageView)

//            if ("1" == isAuth) {
//                imageView.visibility = View.VISIBLE
//                if (!isActDestroy(this@UserCenterActivity))
//                    Glide.with(this@UserCenterActivity).load(url).into(imageView)
//            } else {
//                imageView.visibility = View.GONE
//            }

        }
    }

    private fun doFabAdd() {
        when (mViewPager.currentItem) {
            0 -> {
                VideoPublishActivity.forward(this)
            }
            1 -> {
                MyPhotoPubActivity.forward(this)
            }
            2 -> {
                DynamicPublishActivity.forward(this)
            }
        }
    }


    private val pageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            super.onPageSelected(position)
//            llMine.setVisible(mTypeMine && position != 3)
        }
    }


    /**
     * 根据百分比改变颜色透明度
     */
    private fun changeAlpha(color: Int, fraction: Float): Int {
        val alpha = (Color.alpha(color) * fraction).toInt()
        return Color.argb(alpha, 22, 23, 34)
    }

    private val offsetChangeListener = AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
        val offset = abs(verticalOffset) //目的是将负数转换为绝对正数；
        toolBar.setBackgroundColor(changeAlpha(resources.getColor(R.color.white), abs(verticalOffset * 1.0f) /
                appBarLayout.totalScrollRange))
        /**
         * 当前最大高度便宜值除以2 在减去已偏移值 获取浮动 先显示在隐藏
         */
        /**
         * 当前最大高度便宜值除以2 在减去已偏移值 获取浮动 先显示在隐藏
         */
        if (offset < appBarLayout.totalScrollRange / 2) {
            toolBar.alpha = (appBarLayout.totalScrollRange / 2 - offset * 1.0f) / (appBarLayout.totalScrollRange / 2)
            tvTTitle.text = if (mTypeMine) "个人资料" else "个人资料"
            //shareImg.setAlpha((appBarLayout.totalScrollRange / 2 - Offset * 1.0f) / (appBarLayout.totalScrollRange / 2))
            //shareImg.setImageDrawable(resources.getDrawable(R.mipmap.share_shop))
            /**
             * 从最低浮动开始渐显 当前 Offset就是  appBarLayout.getTotalScrollRange() / 2
             * 所以 Offset - appBarLayout.getTotalScrollRange() / 2
             */
        } else if (offset > appBarLayout.totalScrollRange / 2) {
            val floatX = (offset - appBarLayout.totalScrollRange / 2) * 1.0f / (appBarLayout.totalScrollRange / 2)
            toolBar.alpha = floatX
            tvTTitle.text = nickName
            //shareImg.setAlpha(floate)
            //shareImg.setImageDrawable(resources.getDrawable(R.mipmap.img_share))
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onFollowEvent(e: FollowEvent) {
        if (!mTypeMine) {
            tvEdit2Fav.isSelected = e.isAttention != 1
            tvEdit2Fav.text = if (e.isAttention == 1) "已关注" else "+关注"
        }
    }

    private fun showGift(giftBean: ChatReceiveGiftBean?) {
//        if (mPaused) {
//            return
//        }
        KLog.e("showGift----->", "收到礼物")
        if (mGiftAnimViewHolder == null) {
            mGiftAnimViewHolder = GiftAnimViewHolder(mContext, flLay)
            mGiftAnimViewHolder?.addToParent()
        }
        mGiftAnimViewHolder?.showGiftAnim(giftBean)
    }

    //查看图片
    fun lookImgs(list: ArrayList<String>, selectPos: Int, commonCallback: CommonCallback<Boolean>) {
        val dynamicImgsDialogFragment = DynamicLookImgDialogFragment()
        val bundle = Bundle()
        bundle.putStringArrayList(Constants.DYNAMIC_IMG_LIST, list)
        bundle.putInt(Constants.DYNAMIC_IMG_CUR_POS, selectPos)
        bundle.putString(Constants.DYNAMIC_UID, "")
        dynamicImgsDialogFragment.arguments = bundle
        dynamicImgsDialogFragment.setCommonCallback(commonCallback)
        dynamicImgsDialogFragment.show(supportFragmentManager, "LookDynamicImgsDialogFragment")
    }


    private var mPlayer: TXVodPlayer? = null
    internal var viewGroup: ViewGroup? = null
    internal lateinit var myVideGroup: View
    protected lateinit var mOriginContainer: FrameLayout
    var isOnclick = 0
    private var mVideoView: TXCloudVideoView? = null

    //动态视频放大
    fun addPlayerGroups(container: FrameLayout, videoGroup: View, mVideoView: TXCloudVideoView, img: ImageView, w: Int, h: Int): FrameLayout {
        if (!TextUtils.isEmpty(w.toString()) || w != 0) {


            if (ClickUtil.canClick(300)) {
                isOnclick = 2;
                mOriginContainer = container
                val location = IntArray(2)
                videoGroup.getLocationOnScreen(location)
                val x = location[0]
                val y = location[1]
                this.mVideoView = mVideoView
                mPlayer = TXVodPlayer(this)
                myVideGroup = videoGroup
                viewGroup = videoGroup.parent as ViewGroup
                if (viewGroup != null) {
                    (viewGroup as ViewGroup).removeView(videoGroup)
                }

                videoGroup.setBackgroundResource(com.manor.dynamic.R.color.main_bg)
                resizeVideo(w, h, mVideoView)
                img.visibility = View.GONE
                play_container.addView(videoGroup)
                play_container.setClickable(true)
                play_container.bringToFront()
                videoGroup.setBackgroundResource(com.manor.dynamic.R.color.main_bg)
                val params = FrameLayout.LayoutParams(videoGroup.width, videoGroup.height)
                params.setMargins(x, y, 0, 0)
                videoGroup.layoutParams = params
                val animationa = ViewSizeChangeAnimation(videoGroup, mScreenHeight + ConvertUtils.dp2px( 25f),
                        mScreenWidth, x, y)
                animationa.duration = 500
                videoGroup.startAnimation(animationa)
                animationa.setAnimationListener(object : Animation.AnimationListener {
                    //动画开始的时候触发
                    override fun onAnimationStart(animation: Animation) {

                    }

                    //动画结束的时候触发
                    override fun onAnimationEnd(animation: Animation) {

                    }

                    //动画重新执行的时候触发
                    override fun onAnimationRepeat(animation: Animation) {

                    }
                })
                videoGroup.setOnClickListener {
                    if (ClickUtil.canClick(500)) {
                        viewGroup = videoGroup.parent as ViewGroup
                        if (viewGroup != null) {
                            viewGroup?.removeView(videoGroup)

                        }
                        img.visibility = View.VISIBLE
                        mPlayer?.stopPlay(true)
                        val params = videoGroup.layoutParams as FrameLayout.LayoutParams
                        params.width = container.width
                        params.height = container.height
                        params.setMargins(0, 0, 0, 0)
                        videoGroup.layoutParams = params

                        val sv = mVideoView.layoutParams as FrameLayout.LayoutParams
                        sv.width = container.width
                        sv.height = container.height
                        mVideoView.layoutParams = sv
                        play_container.setClickable(false)
                        container.addView(videoGroup)
                        videoGroup.isClickable = false
                        isOnclick = 1
                    }
                }
            }
        }
        return container
    }


    fun resizeVideo(w: Int, h: Int, mVideoView: TXCloudVideoView) {//放大后给视频加背景
        val mVideoWidth = BigDecimal(w.toString().toString())
        val mVideoHeight = BigDecimal(h.toString().toString())
        KLog.e("tag", "屏幕的宽高" + mScreenWidth + "/" + mScreenHeight + "视频的宽高" + w + "/" + h)
        val istransverse: Boolean
        istransverse = mVideoWidth.compareTo(mVideoHeight) == 1
        val params = mVideoView.layoutParams as FrameLayout.LayoutParams
        if (istransverse) {//如果横屏
            if (mVideoWidth.compareTo(BigDecimal(mScreenWidth.toString() + "")) == 1) {  //如果视频的宽度大于屏幕的快读
                val a = mVideoWidth.subtract(BigDecimal(mScreenWidth.toString()))
                val b = a.divide(BigDecimal(mVideoWidth.toString()), 2, BigDecimal.ROUND_UP)
                val c = b.multiply(BigDecimal(mVideoHeight.toString()))
                val d = BigDecimal(mVideoHeight.toString()).subtract(c)
                params.width = mScreenWidth
                params.height = d.toInt()
            } else run {
                val a = BigDecimal(mScreenWidth.toString() + "").subtract(mVideoWidth)
                val b = a.divide(BigDecimal(mVideoWidth.toString()), 2, BigDecimal.ROUND_DOWN)
                val c = b.multiply(BigDecimal(mVideoHeight.toString()))
                val d = BigDecimal(mVideoHeight.toString()).add(c)
                params.width = mScreenWidth
                params.height = d.toInt()
            }
        } else {
            if (mVideoHeight.compareTo(BigDecimal(mScreenHeight.toString() + "")) == 1) {
                val a = mVideoHeight.subtract(BigDecimal(mScreenHeight.toString()))
                val b = a.divide(BigDecimal(mVideoHeight.toString()), 2, BigDecimal.ROUND_UP)
                val c = b.multiply(BigDecimal(mVideoWidth.toString()))
                val d = BigDecimal(mVideoWidth.toString()).subtract(c)
                params.width = d.toInt()
                params.height = mScreenHeight
            } else run {
                val a = BigDecimal(mScreenHeight.toString().toString()).subtract(mVideoHeight)
                val b = a.divide(BigDecimal(mVideoHeight.toString()), 2, BigDecimal.ROUND_UP)
                val c = b.multiply(BigDecimal(mVideoWidth.toString()))
                val d = BigDecimal(mVideoWidth.toString()).add(c)
                params.width = d.toInt()
                params.height = mScreenHeight
            }

        }
        params.gravity = Gravity.CENTER
        mVideoView.layoutParams = params
    }

    override fun onBackPressed() {
        if (isOnclick == 2) {
            if (play_container.childCount > 0) {
                if (null != viewGroup) {
                    viewGroup = myVideGroup.parent as ViewGroup
                }
                tabLayout.visibility = View.VISIBLE
                viewGroup?.removeView(myVideGroup)
                play_container.isClickable = false

                mOriginContainer.addView(myVideGroup)
                myVideGroup.isClickable = false


                val params = myVideGroup.layoutParams as FrameLayout.LayoutParams
                params.width = mOriginContainer.width
                params.height = mOriginContainer.height
                params.setMargins(0, 0, 0, 0)
                myVideGroup.layoutParams = params


                val sv = mVideoView?.layoutParams as FrameLayout.LayoutParams
                sv.width = mOriginContainer.width
                sv.height = mOriginContainer.height
                mVideoView?.layoutParams = sv
                isOnclick = 1
            } else {
                //UserSvManager.clearDataSource()
                super.onBackPressed()
            }
        } else {
            UserSvManager.clearDataSource()
            super.onBackPressed()
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNewShowGift(e: GiftShowEvent) {
        if (mTypeMine) {
            if (e.giftBean?.uid == mUid)
                showGift(e.giftBean)
        } else {
            if (e.giftBean?.to_uid == mUid)
                showGift(e.giftBean)
        }

    }


}